package org.example.examsystem.controller;


import org.example.examsystem.entity.Teacher;
import org.example.examsystem.service.TeacherService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/teachers")
public class TeacherController {

    private final TeacherService teacherService;

    public TeacherController(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @GetMapping
    public ResponseEntity<Page<Teacher>> getTeachers(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Teacher> teachers = teacherService.getTeachers(pageable);
        return new ResponseEntity<>(teachers, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<String> addTeacher(@RequestBody Teacher teacher) {
        int result = teacherService.addTeacher(teacher);
        if (result > 0) {
            return new ResponseEntity<>("添加成功", HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>("添加失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<String> updateTeacher(@PathVariable int id, @RequestBody Teacher teacher) {
        teacher.setUserid(id);
        int result = teacherService.updateTeacher(teacher);
        if (result > 0) {
            return new ResponseEntity<>("修改成功", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("修改失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteTeacher(@PathVariable int id) {
        int result = teacherService.deleteTeacher(id);
        if (result > 0) {
            return new ResponseEntity<>("删除成功", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("删除失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/batch")
    public ResponseEntity<String> batchDeleteTeachers(@RequestBody List<Integer> ids) {
        int result = teacherService.batchDeleteTeachers(ids);
        if (result > 0) {
            return new ResponseEntity<>("批量删除成功", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("批量删除失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/{userid}")
    public Optional<Teacher> getTeacherById(@PathVariable int userid) {
        return teacherService.findTeacherById(userid);
    }


}